import React, { Component } from 'react'
import { Button, Form, Input, InputNumber, Space } from 'antd'
import TheTable from '@/components/TheTable'
import TheButton from '@/components/TheButton'
import TheDialog from '@/components/TheDialog'
import TheUpload from '@/components/TheUpload'
import TheImage from '@/components/TheImage'
import _ from 'lodash'
import './style/index.less'
import {
  apiGetGoodsClassifyList,
  apiGetGoodsClassifyAdd,
  apiGetGoodsClassifyEdit,
  apiGetGoodsClassifyDel,
} from '@/request/mallManagement'

class Cateory extends Component {
  state = {
    columns0: [
      {
        title: '一级类目',
        dataIndex: 'goodsClassifyName',
        key: 'goodsClassifyName',
      },
      {
        title:'别名',
        dataIndex: "alias",
        key:"alias",
      },
      {
        title: '类目图片',
        dataIndex: 'picture',
        key: 'picture',
        width: 80,
        render: (text, record) => {
          return <TheImage src={text} width={50} height={50} />
        },
      },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <>
              <TheButton haspermi={['mall:category:add']} onClick={(e) => this.addDialog(e, 1, record)}>
                新增
              </TheButton>
              <TheButton haspermi={['mall:category:edit']} onClick={(e) => this.editDialog(e, 0, record)}>
                修改
              </TheButton>
              <TheButton  haspermi={['mall:category:delete']} onClick={(e) => this.delConfirm(e, record, '一')}>
                删除
              </TheButton>
            </>
          )
        },
      },
    ],
    columns1: [
      {
        title: '二级类目',
        dataIndex: 'goodsClassifyName',
        key: 'goodsClassifyName',
      },
      {
        title:'别名',
        dataIndex: "alias",
        key:"alias",
      },
      // {
      //   title: '类目图片',
      //   dataIndex: 'picture',
      //   key: 'picture',
      //   render: (text, record) => {
      //     return <TheImage src={text} width={50} height={50} />
      //   },
      // },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <>
              <TheButton haspermi={['mall:category:add']} onClick={(e) => this.addDialog(e, 2, record)}>
                新增
              </TheButton>
              <TheButton haspermi={['mall:category:edit']} onClick={(e) => this.editDialog(e, 1, record)}>
                修改
              </TheButton>
              <TheButton haspermi={['mall:category:delete']} onClick={(e) => this.delConfirm(e, record, '二')}>
                删除
              </TheButton>
            </>
          )
        },
      },
    ],
    columns2: [
      {
        title: '三级类目',
        dataIndex: 'goodsClassifyName',
        key: 'goodsClassifyName',
      },
      {
        title:'别名',
        dataIndex: "alias",
        key:"alias",
      },
      {
        title: '类目图片',
        dataIndex: 'picture',
        key: 'picture',
        width: 80,
        render: (text, record) => {
          return <TheImage src={text} width={50} height={50} />
        },
      },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <>
              <TheButton haspermi={['mall:category:edit']} onClick={(e) => this.editDialog(e, 2, record)}>
                修改
              </TheButton>
              <TheButton haspermi={['mall:category:delete']} onClick={(e) => this.delConfirm(e, record, '三')}>
                删除
              </TheButton>
            </>
          )
        },
      },
    ],
    dataSource: {
      0: [],
      1: [],
      2: [],
    },
    level1Id: '',
    level2Id: '',
    nowLevel: '',
    visible: false,
    editValue: {},
    type: '',
    title: '',
    level: 0,
    sourceId: '',
    addId: '',
    fileList: [],
    changeName: true,
  }
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    const { level, sourceId, changeName } = this.state
    if (!changeName) return
    let res = await apiGetGoodsClassifyList({
      level,
      sourceId: sourceId || '0',
    })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: {
          ...this.state.dataSource,
          [`${level}`]: res.data,
        },
      })
    }
  }
  handleClick = (value) => {
    const { level, goodsClassifyId } = value
    const { level1Id, changeName } = this.state
    if (!changeName) return
    if (parseInt(level) === 0 && level1Id !== goodsClassifyId) {
      this.setState(
        {
          level1Id: goodsClassifyId,
          level2Id: '',
          level: 1,
          sourceId: goodsClassifyId,
          dataSource: {
            ...this.state.dataSource,
            2: [],
          },
        },
        () => this.getData()
      )
    }
    if (parseInt(level) === 1) {
      this.setState(
        {
          level2Id: goodsClassifyId,
          level: 2,
          sourceId: goodsClassifyId,
        },
        () => this.getData()
      )
    }
  }
  setRowClassName = (record) => {
    const { level } = record
    const { level1Id } = this.state
    if (parseInt(level) === 0) {
      return record.goodsClassifyId === this.state.level1Id ? 'active-row' : ''
    }
    if (parseInt(level) === 1 && level1Id) {
      return record.goodsClassifyId === this.state.level2Id ? 'active-row' : ''
    }
  }
  getFileResult = (file) => {
    let picture = file
      .map((v) => {
        if (v.response) {
          if (v.response.code === 0 && v.response.data) {
            return v.response.data
          }
        }
      })
      .join(',')
    this.formRef.setFieldsValue({ picture })
  }
  addDialog = (e, level, value) => {
    e.stopPropagation()
    this.setState({
      nowLevel: level,
      title: '新增分类',
      visible: true,
      type: 'add',
      addId: value.goodsClassifyId,
      changeName: false,
    })
  }
  editDialog = (e, level, value) => {
    e.stopPropagation()
    let fileList = [
      {
        uid: 1,
        name: 'image',
        status: 'done',
        url: value.picture,
      },
    ]
    this.setState({
      title: '修改分类',
      visible: true,
      editValue: value,
      type: 'edit',
      fileList,
      nowLevel: level,
      changeName: false,
    })
  }
  closeDialog = () => {
    this.setState({
      nowLevel: '',
      title: '',
      visible: false,
      type: '',
      editValue: {},
      fileList: [],
      changeName: true,
    })
  }
  delConfirm = (e, value, str) => {
    this.setState({ changeName: false })
    let { goodsClassifyId, level, sourceId } = value
    e.stopPropagation()
    React.$confirm({
      title: `您确认删除此${str}级分类吗？`,
      onOk: async () => {
        let res = await apiGetGoodsClassifyDel({ goodsClassifyId })
        if (res.code === 0) {
          this.setState(
            {
              level,
              sourceId: sourceId || '',
              changeName: true,
            },
            () => {
              React.$message({
                type: 'info',
                content: '删除成功',
              })
              this.getData()
            }
          )
        } else {
          this.setState({
            changeName: true,
          })
        }
      },
      onCancel: () => {
        this.setState({
          changeName: true,
        })
      },
    })
  }
  dialogSave = async (values) => {
    const {
      nowLevel,
      addId,
      type,
      editValue: { goodsClassifyId, sourceId },
    } = this.state
    if (type === 'add') {
      let res = await apiGetGoodsClassifyAdd({
        level: nowLevel,
        sourceId: addId || '0',
        ...values,
      })
      if (res.code === 0) {
        this.setState(
          {
            level: nowLevel,
            sourceId: addId,
          },
          async () => {
            await this.closeDialog()
            React.$message({
              type: 'info',
              content: '新增成功',
            })
            this.getData()
          }
        )
      }
    }
    if (type === 'edit') {
      let res = await apiGetGoodsClassifyEdit({ goodsClassifyId, ...values })
      if (res.code === 0) {
        this.setState(
          {
            level: nowLevel,
            sourceId: sourceId || '',
          },
          async () => {
            await this.closeDialog()
            React.$message({
              type: 'info',
              content: '修改成功',
            })
            this.getData()
          }
        )
      }
    }
  }
  render() {
    const { dataSource, visible, title, nowLevel, editValue, fileList } =
      this.state
    return (
      <div className="p-layout-box">
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <TheButton type="default" size="middle" haspermi={['mall:category:add']} onClick={(e) => this.addDialog(e, 0, '')}>
            新增一级类目
          </TheButton>
        </div>
        <div className="p-layout-content mall-category-second">
          {_.map(dataSource, (v, i) => {
            return (
              <TheTable
                onRow={(record) => {
                  return {
                    onClick: () => this.handleClick(record),
                  }
                }}
                scroll={{ y: '75vh' }}
                rowClassName={this.setRowClassName}
                columns={this.state[`columns${i}`]}
                dataSource={v}
              />
            )
          })}
        </div>
        <TheDialog
          width={400}
          visible={visible}
          title={title}
          footer={null}
          handleCancel={this.closeDialog}>
          <Form
            ref={(ref) => (this.formRef = ref)}
            onFinish={this.dialogSave}
            initialValues={editValue}>
            <Form.Item
              name="goodsClassifyName"
              label="名称"
              rules={[{ required: true }]}>
              <Input maxLength={5} placeholder="请输入名称" />
            </Form.Item>
            <Form.Item
              name="alias"
              label="别名"
              rules={[{ required: true }]}>
              <Input maxLength={5} placeholder="请输入别名" />
            </Form.Item>
            {nowLevel === 2 && (
              <Form.Item
                name="commissions"
                label={'抽成比例'}
                rules={[{ required: true }]}>
                <InputNumber addonAfter="%" precision={0} min={0} max={100} />
              </Form.Item>
            )}
            {(nowLevel === 0 || nowLevel === 2) && (
              <Form.Item
                name="picture"
                label={'分类图片'}
                rules={[{ required: true }]}>
                <TheUpload
                    isConversion={false}
                  len={1}
                  fileList={fileList}
                  getFileResult={this.getFileResult}
                />
              </Form.Item>
            )}
            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginBottom: -30,
                }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
      </div>
    )
  }
}

export default Cateory
